/**
 * Writed by yura and mak
 */

package wz.legend.handlers.steps;

import org.apache.log4j.Logger;

import wz.legend.Context;
import wz.legend.HttpContext;
import wz.legend.util.ScriptStarter;


public class ClickingStep extends AbstractStep {

    private static final Logger LOG = Logger.getLogger(ClickingChatStep.class);

    String actionName = null;
    String waitUri = "";
    String paramsName = null;
    boolean startAsync = false;

    public ClickingStep() {

    }

    public void execute(Context context) {
        LOG.debug("ClickingStep START");
        String[] params = new String[0];
        state = State.START;
        if (paramsName != null && !"".equals(paramsName)) {
            params = (String[]) context.getProperty(paramsName);
        }
        if (startAsync) {
            context.getScriptStater().doScriptAsync(actionName, params);
        } else {
            context.getScriptStater().doScript(actionName, params);
        }
    }

    public void handle(HttpContext httpContext, Context context) {
        try {
            String uri = "";
            if (httpContext != null) {
                uri = httpContext.getRequest().getRequestLine().getUri();
            }
            if ((uri.contains(waitUri) || ("".endsWith(waitUri) && httpContext == null))
                    && state == State.START) {
                LOG.debug("ClickingStep STOPED");
                state = State.STOPED;
            }
        } catch (Exception e) {
            LOG.error(e, e);
            throw new RuntimeException(e);
        }
    }

    public String getActionName() {
        return actionName;
    }

    public void setActionName(String actionName) {
        this.actionName = actionName;
    }

    public String getWaitUri() {
        return waitUri;
    }

    public void setWaitUri(String waitUri) {
        this.waitUri = waitUri;
    }

    public boolean isStartAsync() {
        return startAsync;
    }

    public void setStartAsync(boolean startAsync) {
        this.startAsync = startAsync;
    }

    public String getParamsName() {
        return paramsName;
    }

    public void setParamsName(String paramsName) {
        this.paramsName = paramsName;
    }
}
